package main;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import com.githang.statusbar.StatusBarCompat;
import com.hichip.campro.R;
import com.hichip.sdk.HiChipSDK;
import com.tencent.android.tpush.XGPushManager;
import java.io.File;
import bean.MyCamera;
import common.DatabaseManager;
import common.HiDataValue;
import custom.dialog.NiftyDialogBuilder;
import custom.drawlayout.SlidingFragmentActivity;
import custom.drawlayout.SlidingMenu;
import utils.ActivityManager;
import utils.HiTools;
/**
 * 主界面
 * Created by lt on 2017\12\14 0014.
 */
public class MainActivity extends SlidingFragmentActivity {
    private Fragment mContent;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActivityManager.getInstance().addActivity(this);
        //设置状态栏为白色底 状态栏字体为黑色
        StatusBarCompat.setStatusBarColor(this, Color.parseColor("#FFFFFF"), true);

        //检查App所有要用到的权限
        checkPermissionAll();
        HiDataValue.ANDROID_VERSION = HiTools.getAndroidVersion();
        initSlidingMenu(savedInstanceState);
        //从数据库读取保存的摄像机列表
        initCamera();
    }

    private void initCamera() {
        DatabaseManager manager = new DatabaseManager(this);
        SQLiteDatabase db = manager.getReadableDatabase();
        Cursor cursor = db.query(DatabaseManager.TABLE_DEVICE, new String[]{"dev_nickname", "dev_uid", "view_acc", "view_pwd", "dev_videoQuality", "dev_alarmState", "dev_pushState", "dev_serverData"}, null, null, null, null, null);
        try {
            while (cursor != null && cursor.moveToNext()) {
                String dev_nickname = cursor.getString(0);
                String dev_uid = cursor.getString(1);
                // 兼容很久之前老版本,没有做UID装换和添加"-"的版本
                dev_uid = dev_uid.toUpperCase();
                dev_uid = HiTools.handUid(dev_uid);
                if (TextUtils.isEmpty(dev_uid)) {
                    throw new IllegalArgumentException("--UID invalid--");
                }
                String dev_name = cursor.getString(2);
                String dev_pwd = cursor.getString(3);
                int dev_videoQuality = cursor.getInt(4);
                int dev_alarmState = cursor.getInt(5);
                int dev_pushState = cursor.getInt(6);
                String dev_serverData = cursor.getString(7);
                MyCamera camera = new MyCamera(getApplicationContext(), dev_nickname, dev_uid, dev_name, dev_pwd);
                camera.setVideoQuality(dev_videoQuality);
                camera.setAlarmState(dev_alarmState);
                camera.setPushState(dev_pushState);
                camera.snapshot = loadImageFromUrl(MainActivity.this, camera);
                camera.setServerData(dev_serverData);
                camera.saveInCameraList();
            }
        } catch (Exception e) {
            // 删除snapshot数据;
            // initCamera();
        } finally {
            cursor.close();
            cursor = null;
            db.close();
        }
        //   requestEnd();
    }


    public void requestEnd() {
        // 获取数据完毕，发送广播到CameraFragment界面去刷新adapter
        Intent intent = new Intent();
        intent.setAction(HiDataValue.ACTION_CAMERA_INIT_END);
        sendBroadcast(intent);
    }

    private void checkPermissionAll() {
        HiDataValue.ANDROID_VERSION = HiTools.getAndroidVersion();
        if (HiDataValue.ANDROID_VERSION >= 6) {
            HiTools.checkPermissionAll(MainActivity.this);
        }
    }

    /**
     * 初始化侧边栏
     */
    private void initSlidingMenu(Bundle savedInstanceState) {
        // 如果保存的状态不为空则得到之前保存的Fragment，否则实例化MyFragment
        if (savedInstanceState != null) {
            mContent = getSupportFragmentManager().getFragment(savedInstanceState, "mContent");
        }

        if (mContent == null) {
            mContent = new CameraFragment();
        }
        getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, mContent).commit();

        // 设置左侧滑动菜单
        setBehindContentView(R.layout.menu_frame_left);
        getSupportFragmentManager().beginTransaction().replace(R.id.menu_frame, new LeftFragment()).commit();

        // 实例化滑动菜单对象
        SlidingMenu sm = getSlidingMenu();
        // 设置可以左右滑动的菜单
        sm.setMode(SlidingMenu.LEFT);
        // 设置滑动阴影的宽度
        sm.setShadowWidthRes(R.dimen.shadow_width);
        // 设置滑动菜单阴影的图像资源
        sm.setShadowDrawable(null);
        // 设置滑动菜单视图的宽度
        sm.setBehindOffsetRes(R.dimen.slidingmenu_offset);
        // 设置渐入渐出效果的值
        sm.setFadeDegree(0.0f);
        // 设置触摸屏幕的模式,这里设置为全屏
        sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
        // 设置下方视图的在滚动时的缩放比例
        sm.setBehindScrollScale(0.5f);

    }


    public Bitmap loadImageFromUrl(Context context, MyCamera camera) {
        // 是否SD卡可用
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            // 检查是或有保存图片的文件夹，没有就创建一个
            String FileUrl = HiDataValue.getPathCameraThumbnail(camera.getUid(),context);
            File folder = new File(FileUrl);
            if (!folder.exists()) {
                folder.mkdirs();
            }
            File f = new File(FileUrl + camera.getUid());
            // SD卡中是否有该文件，有则直接读取返回
            if (f.exists()) {
                BitmapFactory.Options opts=new BitmapFactory.Options();
                opts.inPreferredConfig=Bitmap.Config.RGB_565;
                //先不抽像素
//                if(f.length()>500*1024){
//                    opts.inSampleSize = 3;
//                }else {
//                    opts.inSampleSize = 2;
//                }
                Bitmap bitmap=BitmapFactory.decodeFile(f.getAbsolutePath(),opts);
                return bitmap;
            } else {
                return null;
            }
        }

        return null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        XGPushManager.unregisterPush(this);//信鸽      反注册
        for (final MyCamera camera : HiDataValue.CameraList) {
            if (camera.isSetValueWithoutSave()) {
                camera.updateInDatabase(this);
            }
            DatabaseManager db = new DatabaseManager(MainActivity.this);
            if (db != null) {
                db.updateAlarmStateByUID(camera.getUid(), 0);
            }
            camera.unregisterIOSessionListener();
            new Thread() {
                public void run() {
                    camera.disconnect();//有点耗时  阻塞
                }
            }.start();
        }
        HiChipSDK.uninit();
        //杀掉进程,可以让app白屏时间更短,camera 列表不会重复。
        int pid = android.os.Process.myPid();
        android.os.Process.killProcess(pid);
    }

    @Override
    public void onBackPressed() {
        final NiftyDialogBuilder dialog = NiftyDialogBuilder.getInstance(MainActivity.this);
        dialog.withMessage(getString(R.string.sure_to_exit)).setButton1Click(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        }).setButton2Click(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                ActivityManager.getInstance().clearAll();
            }
        }).show();
    }
}








